#!/usr/bin/env python3
"""
Script to create a superuser.
"""
import asyncio
import sys
from getpass import getpass

from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import AsyncSessionLocal
from app.core.security import get_password_hash
from app.models.user import User
from app.services.user_service import UserService


async def create_superuser():
    """Create a superuser interactively."""
    print("Creating superuser...")
    
    # Get user input
    email = input("Email: ").strip()
    if not email:
        print("Email is required!")
        return
    
    username = input("Username: ").strip()
    if not username:
        print("Username is required!")
        return
    
    full_name = input("Full name (optional): ").strip() or None
    
    password = getpass("Password: ")
    if not password:
        print("Password is required!")
        return
    
    password_confirm = getpass("Password (again): ")
    if password != password_confirm:
        print("Passwords don't match!")
        return
    
    async with AsyncSessionLocal() as db:
        try:
            # Check if user already exists
            existing_user = await UserService.get_user_by_email(db, email)
            if existing_user:
                print(f"User with email {email} already exists!")
                return
            
            existing_user = await UserService.get_user_by_username(db, username)
            if existing_user:
                print(f"User with username {username} already exists!")
                return
            
            # Create superuser
            hashed_password = get_password_hash(password)
            superuser = User(
                email=email,
                username=username,
                full_name=full_name,
                hashed_password=hashed_password,
                is_active=True,
                is_superuser=True,
            )
            
            db.add(superuser)
            await db.commit()
            await db.refresh(superuser)
            
            print(f"Superuser {username} created successfully!")
            
        except Exception as e:
            print(f"Error creating superuser: {e}")
            await db.rollback()


if __name__ == "__main__":
    asyncio.run(create_superuser())